<?php
/**
 * CreateTime: 2023/5/31 10:14
 */

namespace App\Tools\ShortLink;

use App\Models\ShortLink\ShortLinkModel;

class ShortLinkFunc
{
    public static function coverShortUrl($url,$count = 0){
        // 校验当前短链接是否存在
        static $flag = true;
        static $shortUrlModel;
        if($flag){
            $shortUrlModel = new ShortLinkModel();
            $flag = false;
        }

        try {
            $result = [];
            $i = 0;
            while($i<10){
                $md5Url = substr(md5($url.time().$count),0,8);
                $isExists = $shortUrlModel->isExistByCondition([
                    'short_link_code' => $md5Url
                ]);
                if($isExists){
                    continue;
                }
                $res = $shortUrlModel->add([
                    'short_link_code' => $md5Url,
                    'url' => $url
                ]);
                if($res){
                    $result =  [
                        'res_id' =>   $res,
                        'short_link_code' => $md5Url,
                        'url' => $url
                    ];
                    break;
                }
                $i++;
            }
            return $result;
        }catch (\Exception $exception){
            dd($exception);
        }


    }
}